import { USER_STORE } from '@/config/store'
import warmth from '@/common/warmth'
import { StorageEnum } from '@/common/enums'
import type { MenuResponse } from '@interface'

/**
 * 为数组添加 id 字段
 */
export const insertId = <T = any>(arr: Array<T>): Array<T & { id: string }> => {
  const result = arr.map((item, index) => {
    return {
      ...item,
      id: `${index + 1}`,
    }
  })
  return result
}

/**
 * 为数组递归添加 index 字段
 */
export const deepInsertIndex = <T = any>(
  arr: Array<T>,
  firstIndex?: string,
): Array<T & { index: string }> => {
  const result: (T & { index: string; children?: any[] })[] = [...arr].map(
    (v) => ({
      ...v,
      index: '',
    }),
  )

  for (let i = 0; i < result.length; i++) {
    if (firstIndex) {
      const index = `${firstIndex}-${i + 1}`
      result[i].index = index
    } else {
      const index = `${i + 1}`
      result[i].index = index
    }
    if (result[i].children) {
      // @ts-ignore
      deepInsertIndex(result[i].children, result[i].index)
    }
  }

  return result
}

/**
 * 向数组递归添加 index 字段
 */
export const deepIndex = (arr: any[]) => {
  const result = arr.map((v) => v)
  const loop = (arr: any[], parentIndex?: string) => {
    arr.forEach((item, index) => {
      index += 1
      item.index = parentIndex ? `${parentIndex}-${index}` : `${index}`
      if (item.children) {
        loop(item.children, item.index)
      }
    })
  }
  loop(result)
  return result
}

export const deepId = (arr: any[]) => {
  const result = arr.map((v) => v)
  let id = 1
  const loop = (arr: any[]) => {
    arr.forEach((item) => {
      item.id = id
      id += 1
      if (item.children) {
        loop(item.children)
      }
    })
  }
  loop(result)
  return result
}

/**
 * 获取时间函数
 */
type Format = 'YYYY-MM-DD HH:mm:ss' | 'YYYY-MM-DD' | 'HH:mm:ss'
export const getDate = (format: Format): string => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份补零
  const day = String(now.getDate()).padStart(2, '0') // 日期补零
  const hours = String(now.getHours()).padStart(2, '0') // 小时补零
  const minutes = String(now.getMinutes()).padStart(2, '0') // 分钟补零
  const seconds = String(now.getSeconds()).padStart(2, '0') // 秒补零

  switch (format) {
    case 'YYYY-MM-DD HH:mm:ss':
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    case 'YYYY-MM-DD':
      return `${year}-${month}-${day}`
    case 'HH:mm:ss':
      return `${hours}-${minutes}-${seconds}`
  }
}

/**
 * 获取浏览器内存的值
 */
export const getLocalStorage = <T = any>(key: string): T | null => {
  const storage = window.localStorage.getItem(key)
  if (!storage) {
    return null
  }
  return JSON.parse(storage)
}

/**
 * 判断用户是否登陆
 */
export const hasIsUserLogin = () => {
  return !!getLocalStorage(USER_STORE)
}

/**
 * 随机获取今日金句
 */
export const getDayWarmth = () => {
  const len = warmth.length
  const random = Math.floor(Math.random() * len)
  return warmth[random]
}

/**
 * 判断当前运行的浏览器环境
 * edge | chrome | firefox
 */

/**
 * 判断当前运行的平台
 * pad | web | phone
 */
export const getOS = () => {
  const userAgent = window.navigator.userAgent
  const platform = window.navigator.platform

  if (/Mac/i.test(platform)) {
    return 'MacOS'
  }
  if (/Win/i.test(platform)) {
    return 'Windows'
  }
  if (/Linux/i.test(platform)) {
    return 'Linux'
  }
  if (/Android/i.test(userAgent)) {
    return 'Android'
  }
  if (/iPhone|iPad|iPod/i.test(userAgent)) {
    return 'iOS'
  }
  return 'Unknown OS'
}

// 深度搜索数组中的值
export const deepSeekArrayValue = <T = any>(
  source: Array<T>,
  target: string,
  prop = 'index',
): T => {
  let result: any = {}
  const deep = (source: Array<T>, target: string) => {
    // todo: 找到对应的元素应该停止循环
    source.forEach((item: any) => {
      if (`${item[prop]}` === `${target}`) {
        result = item
      }
      if (Array.isArray(item.children)) {
        deep(item.children, target)
      }
    })
  }
  deep(source, target)
  return result
}

/**
 * 将用户信息和token缓存到浏览器
 */
export const setUserInfo = (token: string, userInfo: any) => {
  window.localStorage.setItem(StorageEnum.AUTH_TOKEN, token)
  window.localStorage.setItem(StorageEnum.USER_INFO, JSON.stringify(userInfo))
}

export const formatTime = (time: string) => {
  return new Date(time).toLocaleString('zh-CN')
}

/**
 * 修改网页主题
 */
export const setTheme = (theme: 'dark' | 'light') => {
  const html = document.querySelector('html')
  if (html) {
    html.setAttribute('data-theme', theme)
  }
  /**
   *  element-puls支持的暗黑模式
   *  @see: https://element-plus.org/zh-CN/guide/dark-mode.html
   */
  html?.classList.add(theme)
}

const getModules = () => {
  const modules = import.meta.glob('/src/views/**/*.vue')
  return modules
}

/**
 * 将后端返回的路由表转为router
 */
export const dynamicRouter = async (routes: MenuResponse[]) => {
  const modules = getModules()
  return routes.map((route) => {
    const newItem = {
      path: route.path,
      name: route.name,
      component: modules[`/src/views/${route.component}/index.vue`],
      meta: {
        ...route.meta,
        // 页面刷新时，高亮当前选中
        id: route.id,
      },
    }
    return newItem
  })
}

/**
 * 将后端返回的路由表转为Aside
 */
export const dynamicAside = (routes: MenuResponse[]) => {
  // 获取侧边栏数据
  const asides = routes.filter((v) => v.isSidebar)
  const newAsides = asides.map((item) => {
    return {
      pid: item.pid,
      id: item.id,
      disabled: false,
      name: item.name,
      path: item.path,
      children: [],
    }
  })
  const pidRoutes = newAsides.filter((route) => route.pid)
  const noPidRoutes = newAsides.filter((route) => !route.pid)
  const navbar = noPidRoutes.map((route) => {
    return {
      ...route,
      children: pidRoutes.filter((r) => r.pid === route.id),
    }
  })
  return deepIndex(navbar)
}
